<script setup>
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores/user'
import { fixCoverImageUrl } from '@/utils/fixImageUrls'
import { nameLengthValidator, phoneNumberValidator } from '@/utils/validator'
import { addPropertyServiceDetail, getPropertyServiceDetail } from '@/api/me'
import { upload } from '@/utils/request'

const store = useUserStore()
const form = ref(null)
const propertyForm = ref({
  merchant: '',
  name: '',
  phone: '',
  content: '',
  files: [],
  status: null,
})
const propertyFormRules = {
  merchant: [{ required: true, message: '请填写商家名称' }],
  name: [
    { required: true, message: '请填写姓名' },
    { message: '姓名至少两个字符', validator: nameLengthValidator },
  ],
  phone: [
    { required: true, message: '请填写联系电话' },
    { validator: phoneNumberValidator, message: '手机号格式有误' },
  ],
  content: [{ required: true, message: '请填写物业服务内容' }],
}
const fileList = ref([])

// 是否为新增
const isAdd = computed(() => propertyForm.value.status === null)
async function onGetPropertyServiceDetail(propertyId) {
  try {
    await uni.showLoading({ title: '请稍后' })
    const { result } = await getPropertyServiceDetail(propertyId)
    propertyForm.value = {
      ...result,
      files: result.files.map(item => ({ src: fixCoverImageUrl(item) })),
    }
    uni.hideLoading()
  }
  catch (e) {
    await uni.showToast({ icon: 'none', title: '获取物业服务详情失败' })
  }
}

const showImg = ref(false)
const currentShowImg = ref(0)
function onShowImg(index) {
  currentShowImg.value = index
  showImg.value = true
}

async function beforeUpload(_, options) {
  try {
    const { id } = await upload(options, {
      module: 'property',
      type: 'file',
      single: 'false',
      filetypes: 'jpg,jpeg,png,mp4,doc,docx,pdf',
    })

    propertyForm.value.files.push(id)
  }
  catch (e) {
    await uni.showToast({ icon: 'none', title: e.message, duration: 2000 })
  }
}

function onDelete(_, __, index) {
  propertyForm.value.files.splice(index, 1)
}

const confirmVisible = ref(false)
function onValidate() {
  form.value.validate().then(({ valid }) => {
    if (valid)
      confirmVisible.value = true
  })
}

async function onSubmit() {
  try {
    await uni.showLoading({ title: '请稍后' })
    await addPropertyServiceDetail(propertyForm.value)
    await uni.redirectTo({ url: '/pages/me/view/success?type=物业服务申请' })
    uni.hideLoading()
  }
  catch (e) {
    await uni.showToast({ icon: 'none', title: e.message, duration: 2000 })
  }
}

onLoad(({ propertyId }) => {
  if (propertyId) {
    onGetPropertyServiceDetail(propertyId)
  }
  else {
    propertyForm.value.name = store.userInfo.realName
    propertyForm.value.phone = store.userInfo.phone
    propertyForm.value.merchant = store.userInfo.merchantName
  }
})
</script>

<template>
  <view class="bg-[#F5F5F5] pb-safe min-h-safe">
    <nut-navbar title="物业服务申请" custom-color="#000" left-show placeholder fixed />
    <view class="mt-2">
      <!-- 新增 -->
      <view>
        <nut-config-provider :theme-vars="{ 'input-disabled-color': '#000', 'textarea-disabled-color': '#000', 'cellColor': '#000', 'cellAfterBorderBottom': '1px solid #ccc' }">
          <nut-form ref="form" :model-value="propertyForm" :rules="isAdd ? propertyFormRules : {}" :disabled="!isAdd">
            <nut-form-item label="商&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;家" prop="merchant">
              <nut-input v-model="propertyForm.merchant" placeholder="请输入商家" type="text" />
            </nut-form-item>
            <nut-form-item label="姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名" prop="name">
              <nut-input v-model="propertyForm.name" placeholder="请输入姓名" type="text" />
            </nut-form-item>
            <nut-form-item label="联系电话" prop="phone">
              <nut-input v-model="propertyForm.phone" placeholder="请输入联系电话" type="text" />
            </nut-form-item>
            <nut-form-item label="物业服务" prop="content">
              <nut-textarea
                v-model="propertyForm.content"
                placeholder="请输入物业服务内容"
                type="text"
                max-length="500"
                :limit-show="isAdd"
                :autosize="{ maxHeight: 200, minHeight: 150 }"
              />
            </nut-form-item>
          </nut-form>
        </nut-config-provider>
        <view class="px-4 bg-white">
          <view class="mb-4.5">
            <view class="py-2 text-[#666] flex items-center">
              <view class="i-heroicons:paper-clip-solid text-45" />
              <view class="ml-2 text-28">
                附件
              </view>
            </view>
            <nut-config-provider :theme-vars="{ dividerMargin: 0 }">
              <nut-divider :custom-style="{ color: '#ccc' }" />
            </nut-config-provider>
          </view>
          <view v-if="isAdd">
            <nut-uploader v-model:file-list="fileList" multiple maximum="2" :before-upload="beforeUpload" @delete="onDelete">
              <template #uploadIcon>
                <nut-icon name="uploader" />
              </template>
            </nut-uploader>
            <view class="py-8.75 flex justify-center">
              <nut-button
                block
                :custom-style="{ width: '350rpx' }"
                custom-color="linear-gradient(to right, #F89201, #F83600)"
                @click="onValidate"
              >
                提交申请
              </nut-button>
            </view>
          </view>
          <view v-if="!isAdd && propertyForm.files.length > 0" class="pb-8.75 flex justify-around">
            <image
              v-for="(item, index) in propertyForm.files"
              :key="item.src"
              class="h-189 w-335"
              :src="item.src"
              mode="aspectFill"
              @click="onShowImg(index)"
            />
            <nut-image-preview :show="showImg" :images="propertyForm.files" :init-no="currentShowImg" @close="showImg = false" />
          </view>
        </view>
        <nut-dialog v-model:visible="confirmVisible" content="确认提交吗?" @ok="onSubmit" />
      </view>
    </view>
  </view>
</template>

<style scoped>
:deep(.nut-form-item__label) {
  font-weight: 500;
}
</style>
